package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.YiYuanAESUtils;
import com.block.datapush.service.apipush.utils.YiYuanHuDong;
import com.block.datapush.service.apipush.utils.YunQiUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 亿源互动
 */
@Service
public class YiYuanHuDongService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    MerchantThirdBaseInfoMapper merchantThirdBaseInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        String city = memberSourceInfo.getCity();

        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }


        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("accumulation", YiYuanHuDong.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("car", YiYuanHuDong.getCar(memberSourceInfo.getCar()));
        bizMap.put("cityName", city);
        bizMap.put("creditCard", YiYuanHuDong.getxyk(memberSourceInfo.getXinyongka()));
        bizMap.put("house", YiYuanHuDong.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("huabei", YiYuanHuDong.gethuabei(memberSourceInfo.getHuabei()));
        bizMap.put("insurance", YiYuanHuDong.getbaoxian(memberSourceInfo.getBaoxian()));
        bizMap.put("loanAmount", YiYuanHuDong.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("newSesameSeed", YiYuanHuDong.getzhima(memberSourceInfo.getZhima()));
        bizMap.put("occupation", YiYuanHuDong.getgongzuo(memberSourceInfo.getGongzuo()));
        bizMap.put("overdueSituation", YiYuanHuDong.getYuqi(memberSourceInfo.getYuqi()));
        bizMap.put("provinceName", memberSourceInfo.getProvince());
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? "1" : "2");
        bizMap.put("socialSecurity",YiYuanHuDong.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("userIp",memberSourceInfo.getReqIp());
        bizMap.put("userName",memberSourceInfo.getRealname());
        bizMap.put("userPhone",memberSourceInfo.getMobileMd5().toUpperCase());
        bizMap.put("whiteStripe",YiYuanHuDong.getbaitiao(memberSourceInfo.getBaitiao()));


        String dataJson = JSON.toJSONString(bizMap);

        String dataKey=pushApiKeyParam.getApiKey();//EEAC000D9C76FF84
        String signKey=pushApiKeyParam.getApiSecret();  //B94086173175D0BE
        String encryptData = YiYuanAESUtils.encode(YiYuanAESUtils.encode(dataJson, dataKey));
        String sign = DigestUtils.shaHex(dataJson + signKey);

        long timestamp = System.currentTimeMillis();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("systemCode", pushApiKeyParam.getApiCode());
        paramMap.put("action","fullAuthMatch");
        paramMap.put("requestId","TD-" + timestamp);
        paramMap.put("signData", sign);
        paramMap.put("encryptData", encryptData);




        log.info("【亿源互动】撞库开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【亿源互动撞库】撞库结束【resultDes】{}", resultObject.toJSONString());

        // 检查并获取encryptData字段
        if (!resultObject.containsKey("encryptData")) {

            pushApiResult.setMessage(resultObject.toJSONString());
            return pushApiResult;
        }

        String encryptDatas = resultObject.getString("encryptData");

        String resultObject1 = YiYuanAESUtils.decode(YiYuanAESUtils.decode(encryptDatas),dataKey);



        JSONObject resultObject2 = JSON.parseObject(resultObject1);
        log.info("【亿源互动】撞库结束【resultDes】{}", resultObject2.toJSONString());

        String responseCode = resultObject2.getString("responseCode");
        String responseMsg = resultObject2.getString("responseMsg");


        pushApiResult.setCode(responseCode);
        pushApiResult.setMessage(responseMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(responseCode, "000000")) {
            JSONObject result1 = resultObject2.getJSONObject("result");
            String resultMsg = result1.getString("resultMsg");
            String resultCode = result1.getString("resultCode");
            pushApiResult.setCode(responseCode + "|" + resultCode);
            pushApiResult.setMessage(responseMsg + "|" + resultMsg);

            if(StrUtil.equals(resultCode,"000000")){
                String serialNo = UUID.randomUUID().toString();
                ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
                thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
                thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
                thirdInfoDTO.setOrderNo(orderNo);
                String productName = result1.getString("exhibitionName");
                JSONObject infoObject = new JSONObject();
                infoObject.put("orderNo", serialNo);
                infoObject.put("productId", serialNo);
                infoObject.put("productName", productName);
                infoObject.put("companyName", productName);
                infoObject.put("companyLogo", pushApiKeyParam.getQueryUrl());
                infoObject.put("maxLoanAmount", "100000");
                infoObject.put("maxLoanRate", "20");
                infoObject.put("minLoanRate", "1");
                infoObject.put("businessInfo", pushApiKeyParam.getInfoName());
                JSONArray jsonArray = new JSONArray();
                infoObject.put("protocalList", jsonArray);
                thirdInfoDTO.setInfoObject(infoObject);

                boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
                if (save) {
                    pushApiResult.setPushSuccess(true);
                    pushApiResult.setOutOrderNo(serialNo);
                } else {
                    pushApiResult.setMessage("保存撞库数据失败");
                }

            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);


        String requestUrl = pushApiKeyParam.getRegisterUrl();

        String city = memberSourceInfo.getCity();

        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("accumulation", YiYuanHuDong.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("car", YiYuanHuDong.getCar(memberSourceInfo.getCar()));
        bizMap.put("cityName", city);
        bizMap.put("creditCard", YiYuanHuDong.getxyk(memberSourceInfo.getXinyongka()));
        bizMap.put("house", YiYuanHuDong.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("huabei", YiYuanHuDong.gethuabei(memberSourceInfo.getHuabei()));
        bizMap.put("insurance", YiYuanHuDong.getbaoxian(memberSourceInfo.getBaoxian()));
        bizMap.put("loanAmount", YiYuanHuDong.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("newSesameSeed", YiYuanHuDong.getzhima(memberSourceInfo.getZhima()));
        bizMap.put("occupation", YiYuanHuDong.getgongzuo(memberSourceInfo.getGongzuo()));
        bizMap.put("overdueSituation", YiYuanHuDong.getYuqi(memberSourceInfo.getYuqi()));
        bizMap.put("provinceName", memberSourceInfo.getProvince());
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? "1" : "2");
        bizMap.put("socialSecurity",YiYuanHuDong.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("userIp",memberSourceInfo.getReqIp());
        bizMap.put("userName",memberSourceInfo.getRealname());
        bizMap.put("userPhone",memberSourceInfo.getMobile());
        bizMap.put("whiteStripe",YiYuanHuDong.getbaitiao(memberSourceInfo.getBaitiao()));


        String dataJson = JSON.toJSONString(bizMap);

        String dataKey=pushApiKeyParam.getApiKey();//EEAC000D9C76FF84
        String signKey=pushApiKeyParam.getApiSecret();  //B94086173175D0BE
        String encryptData = YiYuanAESUtils.encode(YiYuanAESUtils.encode(dataJson, dataKey));
        String sign = DigestUtils.shaHex(dataJson + signKey);

        long timestamp = System.currentTimeMillis();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("systemCode", pushApiKeyParam.getApiCode());
        paramMap.put("action","apply");
        paramMap.put("requestId","TD-" + timestamp);
        paramMap.put("signData", sign);
        paramMap.put("encryptData", encryptData);

        log.info("【亿源互动】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);

        // 检查并获取encryptData字段
        if (!resultObject.containsKey("encryptData")) {

            pushApiResult.setMessage(resultObject.toJSONString());
            return pushApiResult;
        }


        String encryptDatas = resultObject.getString("encryptData");

        String resultObject1 = YiYuanAESUtils.decode(YiYuanAESUtils.decode(encryptDatas),dataKey);

        JSONObject resultObject2 = JSON.parseObject(resultObject1);
        String responseCode = resultObject2.getString("responseCode");
        String responseMsg = resultObject2.getString("responseMsg");

        log.info("【亿源互动】导单结束【result】{}", resultObject2.toJSONString());

        pushApiResult.setCode(responseCode);
        pushApiResult.setMessage(responseMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo);
        thirdInfoDTO.setRetCode(responseCode);
        thirdInfoDTO.setRetMsg(responseMsg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (StrUtil.equals(responseCode,"000000")) {
            JSONObject result1 = resultObject2.getJSONObject("result");
            String resultCode = result1.getString("resultCode");
            if(StrUtil.equals(resultCode,"000000")){
                thirdInfoDTO.setStatus("SUCCESS");
            }
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (StrUtil.equals(responseCode,"000000")) {
            JSONObject result1 = resultObject2.getJSONObject("result");
            String resultCode = result1.getString("resultCode");
            String resultMsg = result1.getString("resultMsg");
            if(StrUtil.equals(resultCode,"000000")){
                pushApiResult.setCode(responseCode + "|" + resultCode);
                pushApiResult.setMessage(responseMsg + "|" + resultMsg);
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

}
